#include <iostream>
#include <string>
#include <vector>
#include <cstdio>
#include <cassert>
#include <pthread.h>
#include <unistd.h>

using namespace std;

class ThreadData
{
public:
    int number;//线程的编号
    pthread_t tid;//线程的tid
    char namebuffer[64];//线程格式化之后的名字   
};

class ThreadReturn 
{
public:
    int exit_code;
    int exit_result;
};

void *start_routine(void *args)
{
    int cnt = 10;
    while(cnt--)
    {
        ThreadData * td = static_cast<ThreadData *>(args);
        cout << "new thread create success, name: " << td->namebuffer << endl;
        sleep(1);
    }
}
int main()
{
    vector<ThreadData*> threads;

    for(int i = 0; i < 10; i++)
    {
        ThreadData *td = new ThreadData;
        td->number = i+1;
        snprintf(td->namebuffer, sizeof(td->namebuffer), "thread: %d", i+1);
        pthread_create(&td->tid, nullptr, start_routine, td);

        threads.push_back(td);

    }

    sleep(5);//5s之后我们取消一半的线程
    for(int i = 0; i < threads.size()/2; i++)
    {
        pthread_cancel(threads[i]->tid);
        cout << "cancel " << threads[i]->namebuffer << " success" << endl;
    }

    void *ret = nullptr;
    for(auto it : threads)
    {
        pthread_join(it->tid, &ret);
        cout << "join : thread:" << it->namebuffer << " success, " << "exit_code:" << (long long)ret << endl;
    }
    cout << "main thread quit!" << endl;

    return 0;
}